package com.superhelper.deliver.task.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.superhelper.common.Consts;
import com.superhelper.common.domain.AuserDeliver;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.DeliverRecord;
import com.superhelper.common.domain.Task;
import com.superhelper.common.mapper.DeliverMapper;
import com.superhelper.common.mapper.DeliverRecordMapper;
import com.superhelper.common.mapper.TaskMapper;
import com.superhelper.common.utils.JsonHelper;

@Component
public class AddTipScanTask {
    private static final Logger log = LoggerFactory.getLogger(AddTipScanTask.class);

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private DeliverRecordMapper recordMapper;

    @Autowired
    private DeliverMapper deliverMapper;

    private List<AuserShop> shops = null;
    private long last;

    @Scheduled(cron = "0/5 * * * * ?")
    public void run() {
        if (shops == null || System.currentTimeMillis() - last >= 60000) {
            shops = deliverMapper.getAllUserShop();
            for (AuserShop shop : shops) {
                AuserDeliver deliverConf = deliverMapper.getAuserDeliver(shop.getAuserId());
                shop.setDeliverConf(deliverConf == null ? AuserDeliver.getDefault() : deliverConf);
            }
            last = System.currentTimeMillis();
        }
        for (AuserShop shop : shops) {
            List<DeliverRecord> records = recordMapper.queryFirstNeedAddTipRecords(shop.getId(),
                    shop.getDeliverConf().getFixed_minute());
            List<DeliverRecord> records2 = recordMapper.queryAfterAddTipNeedMoreRecords(shop.getId(),
                    shop.getDeliverConf().getGt_minute());
            records.addAll(records2);
            for (DeliverRecord record : records) {

                log.info("needAddtip record:{}", JsonHelper.toJson(record));
                if (taskMapper.hasTask(Consts.Task.add_tip, record.getId() + "") > 0) {
                    continue;
                }
                try {
                    taskMapper.addTask(new Task(Consts.Task.add_tip, record.getId() + ""));
                } catch (Exception e) {
                    log.error("error", e);
                }
            }
        }
    }
}
